import os
import httpx


# 获取json数据
def get_json(url, headers, cookies, json_data):
    try:
        with httpx.Client() as client:
            resp = client.post(url=url, headers=headers, cookies=cookies, json=json_data, timeout=4)
            return resp.json()
    except:
        return None


# 解析json数据
def parse_json(json_dict):
    # 短视频标题、作者ID、作者名字、短视频ID、短视频URL
    result_list = []
    feeds = json_dict['data']['brilliantTypeData']['feeds']
    for feed in feeds:
        result_dict = {}

        result_dict['author_id'] = feed['author']['id']
        result_dict['author_name'] = feed['author']['name']
        result_dict['caption'] = feed['photo']['caption']
        result_dict['photo_id'] = feed['photo']['id']
        result_dict['photo_url'] = feed['photo']['photoUrl']

        result_list.append(result_dict)

    return result_list


# 下载视频
def download_photo(feeds, headers):
    for feed in feeds:
        # 请求下载地址url获取二进制数据
        with httpx.Client() as client:
            resp = client.get(url=feed['photo_url'], headers=headers)
            save_photo(resp.content, feed['photo_id'])

        return None

def save_photo(data, filename):
    if not os.path.exists('./视频'):
        os.mkdir('./视频')

    with open('./视频/' + filename + '.mp4', 'wb') as f:
        f.write(data)


def main():
    url = 'https://www.kuaishou.com/graphql'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36',
    }
    cookies = {
        "kpf": "PC_WEB",
        "clientid": "3",
        "did": "web_717ad7a5d13c8afb38e63e8aacaf6e7f",
        "userId": "3498836671",
        "kuaishou.server.web_st": "ChZrdWFpc2hvdS5zZXJ2ZXIud2ViLnN0EqABFsGQq0_BYdyIXKzAAEdcn89-R4PZ5EL1Bcmie5bHwkrQG48YktDMw2fnlh-I1IHZmEC763nZHWEag4YErr7U-8bNfU9R4HFTzfp2BaMYRyb3tOBBiEtft-vX8zTbb0Q-K3Ke85ZctyIwquY3xyDBGiG4HFQRw7aWiAKyoOsMGk12gas53cvyVEgbsFf8dkbodcn5862OCsp45SRGH3fWTxoSsmhEcimAl3NtJGybSc8y6sdlIiBBNMRslUAl6JcK35b-wZaUK68_vE35Vc_Vq2NgOCuRWigFMAE",
        "kuaishou.server.web_ph": "4058b1cbb772546dbb25b4078b39c4495bb6",
        "kpn": "KUAISHOU_VISION"
    }
    json_data = {
        "operationName": "brilliantTypeDataQuery",
        "variables": {
            "hotChannelId": "00",
            "page": "brilliant",
            "pcursor": "1"
        },
        "query": "fragment photoContent on PhotoEntity {\n  id\n  duration\n  caption\n  originCaption\n  likeCount\n  viewCount\n  commentCount\n  realLikeCount\n  coverUrl\n  photoUrl\n  photoH265Url\n  manifest\n  manifestH265\n  videoResource\n  coverUrls {\n    url\n    __typename\n  }\n  timestamp\n  expTag\n  animatedCoverUrl\n  distance\n  videoRatio\n  liked\n  stereoType\n  profileUserTopPhoto\n  musicBlocked\n  __typename\n}\n\nfragment feedContent on Feed {\n  type\n  author {\n    id\n    name\n    headerUrl\n    following\n    headerUrls {\n      url\n      __typename\n    }\n    __typename\n  }\n  photo {\n    ...photoContent\n    __typename\n  }\n  canAddComment\n  llsid\n  status\n  currentPcursor\n  tags {\n    type\n    name\n    __typename\n  }\n  __typename\n}\n\nfragment photoResult on PhotoResult {\n  result\n  llsid\n  expTag\n  serverExpTag\n  pcursor\n  feeds {\n    ...feedContent\n    __typename\n  }\n  webPageArea\n  __typename\n}\n\nquery brilliantTypeDataQuery($pcursor: String, $hotChannelId: String, $page: String, $webPageArea: String) {\n  brilliantTypeData(pcursor: $pcursor, hotChannelId: $hotChannelId, page: $page, webPageArea: $webPageArea) {\n    ...photoResult\n    __typename\n  }\n}\n"
    }
    json_dict = get_json(url, headers, cookies, json_data)
    if json_dict:
        feeds = parse_json(json_dict)
        if feeds:
            download_photo(feeds, headers)


if __name__ == '__main__':
    main()
